﻿using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityServer4.Models;
using K9Nano.Share.Exceptions;
using Microsoft.AspNetCore.Mvc;

namespace K9Nano.Admin.Identity
{
    [ApiController]
    [Route("ApiScope/[Action]")]
    public class ApiScopeController: ControllerBase
    {
        protected readonly IApiScopeAppService Service;

        public ApiScopeController(IApiScopeAppService service)
        {
            Service = service;
        }

        [HttpGet]
        public async Task<IReadOnlyList<ApiScope>> GetAll()
        {
            return await Service.GetAllAsync(HttpContext.RequestAborted);
        }

        [HttpGet]
        public async Task<ApiScope> Get(string name)
        {
            return await Service.GetByNameAsync(name, HttpContext.RequestAborted);
        }

        [HttpPost]
        public async Task AddOrUpdate([FromBody]ApiScope scope)
        {
            if (string.IsNullOrEmpty(scope.Name))
            {
                throw new K9UserFriendlyException("Name 不能为空");
            }

            await Service.AddOrUpdateAsync(scope, HttpContext.RequestAborted);
        }

        [HttpDelete]
        public async Task Delete(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new K9UserFriendlyException("Name 不能为空");
            }

            await Service.DeleteAsync(name, HttpContext.RequestAborted);
        }

        [HttpPost]
        public async Task SetEnable(string name, bool enable)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new K9UserFriendlyException("Name 不能为空");
            }

            await Service.SetEnableAsync(name, enable, HttpContext.RequestAborted);
        }
    }
}